package com.deanlib.cabinet.ui.view;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.HttpMethod;
import com.alibaba.sdk.android.oss.model.GeneratePresignedUrlRequest;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.deanlib.cabinet.R;
import com.deanlib.cabinet.base.BaseActivity;
import com.deanlib.cabinet.data.AppDatabase;
import com.deanlib.cabinet.data.model.Resource;
import com.deanlib.cabinet.data.model.ResourceCache;
import com.deanlib.cabinet.databinding.LayoutMediaGalleryBrowserBinding;
import com.deanlib.cabinet.utils.ConfigManager;
import com.deanlib.cabinet.utils.FileUtilsExt;
import com.deanlib.cabinet.utils.JsonUtils;
import com.deanlib.cabinet.utils.OssManager;
import com.deanlib.plantern.utils.FormatUtils;
import com.deanlib.plantern.utils.PopupUtils;
import com.elvishew.xlog.XLog;
import com.github.chrisbanes.photoview.PhotoView;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.PlayerView;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @Created by Dean
 * @Date 2023/9/7
 */
public class MediaGalleryBrowser extends BaseActivity<LayoutMediaGalleryBrowserBinding> {

    List<Resource> mediaList;
    MediaAdapter mediaAdapter;
    Resource resource;
    SimpleExoPlayer exoPlayer;


    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        String content = getIntent().getStringExtra("resource");
        if (TextUtils.isEmpty(content)) {
            PopupUtils.sendToast(R.string.get_media_fail);
            finish();
        } else {
            resource = JsonUtils.getGson().fromJson(content, Resource.class);
        }
    }

    @Override
    public void initView() {
        binding.vpMedia.setAdapter(mediaAdapter = new MediaAdapter(mediaList = new ArrayList<>()));
    }

    @Override
    public void loadData() {
        if (TextUtils.isEmpty(resource.title)) {
            resource.setTitle(FormatUtils.convertTimestampToString(resource.resCreateTime, FormatUtils.DATE_FORMAT_YMDHMS));
        }
        mediaList.add(resource);
        mediaAdapter.notifyItemInserted(0);
    }

    @Override
    public int getLayoutId() {
        return R.layout.layout_media_gallery_browser;
    }

    class MediaAdapter extends RecyclerView.Adapter<MediaViewHolder> {

        List<Resource> list;

        public MediaAdapter(List<Resource> list) {
            this.list = list;
        }

        @NonNull
        @Override
        public MediaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_media_gallery_item, parent, false);
            return new MediaViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MediaViewHolder holder, int position) {
            Resource resource = list.get(position);
            boolean needNetLoad = false;
            if (FileUtilsExt.isImage(resource.mineType)) {
                holder.pvImage.setVisibility(View.VISIBLE);
                holder.playerView.setVisibility(View.GONE);
                String path = resource.localPath;
                if (!TextUtils.isEmpty(path)) {
                    //本地资源加载
                    Glide.with(holder.pvImage.getContext()).load(path)
                            .apply(RequestOptions.placeholderOf(R.drawable.placeholer).error(R.drawable.error))
                            .into(holder.pvImage);
                } else {
                    //没有本地资源 从网络加载
                    needNetLoad = true;
                }
            } else if (FileUtilsExt.isVideo(resource.mineType)) {
                holder.pvImage.setVisibility(View.GONE);
                holder.playerView.setVisibility(View.VISIBLE);
                String path = resource.localPath;
                if (!TextUtils.isEmpty(path)) {
                    initVideo(holder.playerView, path, resource.getTitle());
                } else {
                    needNetLoad = true;
                }
            }

            if (needNetLoad) {
                String md5 = resource.md5;
                //由于数据结构的变化，存于OSS上的数据资源的名称之前用的压缩后md5值，现在用的是压缩前md5值命名
                //所以在 GetObjectRequest 的第二个参数生成里，需要注意
                if (!resource.path.contains(resource.md5)) {
                    md5 = resource.newMd5;
                }
                if (FileUtilsExt.isImage(resource.mineType)) {
                    //如果是图片，直接下载缓存再展示
                    //下载方式
                    GetObjectRequest request = new GetObjectRequest(
                            ConfigManager.getInstance().getOssKey().extend2,
                            OssManager.createObjKey(md5, resource.path.substring(resource.path.lastIndexOf("."))));
                    OssManager.getInstance().getOssClient().asyncGetObject(request, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
                        @Override
                        public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                            String outFilePath = ResourceCache.createCachePath(resource.md5);
                            if (FileUtilsExt.saveFileByStream(result.getObjectContent(), outFilePath)) {
                                ResourceCache resourceCache = AppDatabase.getDaoSession().getResourceCacheDao().load(resource.md5);
                                if (resourceCache==null){
                                    resourceCache = new ResourceCache();
                                    resourceCache.setMd5(resource.md5);
                                    resourceCache.setCreateTime(System.currentTimeMillis());
                                    resourceCache.setNetPath(resource.path);
                                    resourceCache.setPath(outFilePath);
                                    AppDatabase.getDaoSession().getResourceCacheDao().insert(resourceCache);
                                    XLog.d("save path md5:" +resource.md5 + " local:" + outFilePath);
                                } else if (TextUtils.isEmpty(resourceCache.path)){
                                    resourceCache.setPath(outFilePath);
                                    AppDatabase.getDaoSession().getResourceCacheDao().update(resourceCache);
                                    XLog.d("update path md5:" +resource.md5 + " local:" + outFilePath);
                                }


                                Glide.with(holder.pvImage.getContext()).load(outFilePath)
                                        .apply(RequestOptions.placeholderOf(R.drawable.placeholer).error(R.drawable.error))
//                                            .into(contentHolder.imgPhoto); //这种方式，不显示，需要滚动一下才能显示 ，不知为什么
                                        .into(new CustomTarget<Drawable>() {
                                            @Override
                                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                                holder.pvImage.setImageDrawable(resource);
                                            }

                                            @Override
                                            public void onLoadCleared(@Nullable Drawable placeholder) {

                                            }

                                            @Override
                                            public void onLoadStarted(@Nullable Drawable placeholder) {
                                                super.onLoadStarted(placeholder);
                                                holder.pvImage.setImageDrawable(placeholder);
                                            }

                                            @Override
                                            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                                super.onLoadFailed(errorDrawable);
                                                holder.pvImage.setImageDrawable(errorDrawable);
                                            }
                                        });
                            }else {
                                PopupUtils.sendToast(R.string.get_media_fail);
                            }
                        }

                        @Override
                        public void onFailure(GetObjectRequest request, ClientException clientException, ServiceException serviceException) {
                            clientException.printStackTrace();
                            serviceException.printStackTrace();
                            PopupUtils.sendToast(R.string.get_media_fail);
                        }
                    });
                } else if (FileUtilsExt.isVideo(resource.mineType)) {
                    //视频不能等下载完成再展示，用时太长，所以使用URL的方式直接加载
                    //签名URL方式
                    try {
                        String finalMd5 = md5;
                        addDisposable(Observable.create((ObservableOnSubscribe<String>) emitter -> {
                                    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
                                            ConfigManager.getInstance().getOssKey().extend2,
                                            OssManager.createObjKey(finalMd5, resource.path.substring(resource.path.lastIndexOf("."))));
                                    // 设置签名URL的过期时间，单位秒
                                    request.setExpiration(24 * 60 * 60);
                                    request.setMethod(HttpMethod.GET);
                                    String url = OssManager.getInstance().getOssClient().presignConstrainedObjectURL(request);
                                    emitter.onNext(url);
                                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                .subscribe(url -> {
                                    if (FileUtilsExt.isImage(resource.mineType)) {
                                        Glide.with(holder.pvImage.getContext()).load(url).into(holder.pvImage);
                                    } else if (FileUtilsExt.isVideo(resource.mineType)) {
                                        initVideo(holder.playerView, url, resource.getTitle());
                                    }
                                }));
                    } catch (Exception e) {
                        e.printStackTrace();
                        PopupUtils.sendToast(R.string.get_media_fail);
                    }
                }
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }

    static class MediaViewHolder extends RecyclerView.ViewHolder {
        PhotoView pvImage;
        PlayerView playerView;

        public MediaViewHolder(@NonNull View itemView) {
            super(itemView);
            pvImage = itemView.findViewById(R.id.pvImage);
            playerView = itemView.findViewById(R.id.playerView);
        }
    }

    private void initVideo(PlayerView playerView, String path, String title) {
        //全部使用默认设置初始化ExoPlayer
        exoPlayer = new SimpleExoPlayer.Builder(this).build();
        //将显示控件绑定ExoPlayer
        playerView.setPlayer(exoPlayer);
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/1/12.mp4";
//        File file = new File(path);
//        //构建媒体播放的一个Item， 一个item就是一个播放的多媒体文件
//        MediaItem item = MediaItem.fromUri(Uri.fromFile(file));
//        String path = "https://deanlib-cabinet.oss-cn-zhangjiakou.aliyuncs.com/8/3/6/9/9/83699bf483ce29e642d6ea2cd7e684a7.mp4?Expires=1704184700&OSSAccessKeyId=TMP.3Kj84uvUmVtp4Quti5cymNNova8AC3kGu3rkXJCGqBt5DDW6oPBKSyAdDDJ2Z24VZzd3wR3aToDb6NMEHkSUZMeKFEPa31&Signature=Fxw9UCcwjl8bqq52nZHPAoINrhg%3D";
//        String path = "https://deanlib-cabinet.oss-cn-zhangjiakou.aliyuncs.com/8/3/6/9/9/83699bf483ce29e642d6ea2cd7e684a7.mp4?Expires=1704185425&OSSAccessKeyId=TMP.3Kj84uvUmVtp4Quti5cymNNova8AC3kGu3rkXJCGqBt5DDW6oPBKSyAdDDJ2Z24VZzd3wR3aToDb6NMEHkSUZMeKFEPa31&Signature=EfV%2FU%2BTVn68iCHut10IhOoIwSoM%3D";
//        String path = "https://www.guizhou.gov.cn/mas/openapi/pages.do?method=exPlay&appKey=gov&type=vod&id=218192";
        MediaItem item = MediaItem.fromUri(path);
        //设置ExoPlayer需要播放的多媒体item
        exoPlayer.setMediaItem(item);
        //设置播放器是否当装备好就播放， 如果看源码可以看出，ExoPlayer的play()方法也是调用的这个方法
        exoPlayer.setPlayWhenReady(true);
        //初始化播放位置
//        player.seekTo(currentWindow, playbackPosition);
        //资源准备，如果设置 setPlayWhenReady(true) 则资源准备好就立马播放。
        exoPlayer.prepare();
    }

    @Override
    public void onStart() {
        super.onStart();
//        if (Util.SDK_INT > 23  ) {
//            initVideo();
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (exoPlayer != null) {
            exoPlayer.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (exoPlayer != null) {
            exoPlayer.stop();
            exoPlayer.release();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (Util.SDK_INT <= 23 || exoPlayer == null) {
//            initVideo();
//        }
    }

}
